package com.jerry.chat.controller;

import com.jerry.chat.Ret;
import com.jerry.chat.dao.UserMapper;
import com.jerry.chat.domain.FriendRelationShip;
import com.jerry.chat.domain.User;
import com.jerry.chat.service.FriendRelationShipService;
import com.jerry.chat.service.JPushService;
import com.jerry.chat.service.MinioService;
import com.jerry.chat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/u")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private JPushService jPushService;

    @Autowired
    private MinioService minioService;

    @Autowired
    private FriendRelationShipService friendRelationShipService;

    @PostMapping("/r")
    String register(@RequestBody User user) {
        userMapper.Insert(user);
        return "{status: Succeed}";
    }

    @PostMapping("/l")
    public Ret login(@RequestBody User user) {
        var u = userService.login(user);
        if (u != null) {
            return Ret.succeed().setObject(u);
        } else {
            return Ret.error();
        }
    }

    @PostMapping("/s")
    @ResponseBody
    Ret search(@RequestBody Map<String, String> params) {
        var id = params.get("id");
        var u = userMapper.getById(id);
        if (u == null) {
            return Ret.error().setMsg("Failed to find user with id: " + id.toString());
        }

        return Ret.succeed().setObject(u);
    }

    @PostMapping("/raf")
    Ret requestAddFriend(@RequestBody FriendRelationShip friendRelationShip) {

        var sender = userMapper.getById(friendRelationShip.getId1());
        var receiver = userMapper.getById(friendRelationShip.getId2());
        jPushService.pushMessage(receiver.getCid(), sender.getName(), "请求添加你为朋友", sender.getId());
        return Ret.succeed();
    }

    @PostMapping("/add_friend")
    Ret addFriend(@RequestBody FriendRelationShip friendRelationShip) {
        friendRelationShipService.addFriend(friendRelationShip);
        friendRelationShipService.addFriend(friendRelationShip.swapIds());
        return Ret.succeed();
    }

    @GetMapping("/friend_list")
    public java.util.List<User> getFriendList(String id) {
        return userMapper.getFriendList(id);
    }

    @GetMapping("/upload_file_path")
    public Ret getUploadFilePath(String filename) {
        String path = minioService.getFileUploadPath("chat", filename);
        if (path != "") {
            return Ret.succeed().setMsg(path);
        } else {
            return Ret.error();
        }
    }

    @PutMapping("/update_facepath")
    public Ret updateFacepath(@RequestBody User user) {
        userMapper.updateFacepath(user);
        return Ret.succeed();
    }
}
